package com.leyantech.ecp.agenx.translator.filter.client;

import com.leyantech.ecp.agenx.translator.config.EnumPddMsgType;
import com.leyantech.utility.config.ConfigUtil;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Singleton;
import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-15.
 */
@Slf4j
@Singleton
public class TransferMessageFilter implements ClientMessageFilter {

  /**
   * 转移会话关键字.
   */
  public static final Supplier<List<String>> transferKeyWords = ConfigUtil.getDynamicConfig(
      "transfer_key_words",
      json -> new Gson().fromJson(json, new TypeToken<List<String>>() {
      }.getType()),
      Arrays.asList(" 将该会话转移给 "," 分配给 ")
  );

  @Override
  public boolean test(JsonObject jsonObject) {
    JsonObject body = jsonObject.getJsonObject("body");
    JsonObject message = body.getJsonObject("message");
    // 登录登出消息没有 message
    if (message == null) {
      return true;
    }

    Object type = message.getValue("type");
    if (Objects.isNull(type) || (int) type != EnumPddMsgType.ASSISTANT_TRANSFER_MSG.typeNo) {
      return true;
    }
    log.debug("TransferMessageFilter message: {}", jsonObject);
    String sid = body.getString("sid");
    String aid = body.getString("aid");

    // 不论方向，只要是 转移消息，都走这个逻辑
    if (transferKeyWords.get().stream().noneMatch(message.getString("content")::contains)
        || !aid.equals(message.getJsonObject("info").getString("target_id"))) {
      // 对于转接消息，我们只接受被转接的客服的消息
      log.info("收到转接消息 并且不做回传. {}, {}, msg: {}", sid, aid,
          message.getString("content"));
      return false;
    }
    return true;
  }

}
